from google.appengine.api import users
from plzkeepthat.common import messages
from plzkeepthat.common.util import get_notelist
from plzkeepthat.controller.util import mailutils as mail
from plzkeepthat.controller.util.parserutils import NoteParser, get_add_form
from plzkeepthat.models.util import dbutils
from plzkeepthat.models.util.dbutils import get_note_by_id, save_note, \
    delete_note_by_id, is_valid_tag, get_tags_for_note
from plzkeepthat.views import views
from plzkeepthat.views.forms import forms
from plzkeepthat.views.util.webutils import Messages
import logging


#===============================================================================
# Page controller - handles all events 
#===============================================================================

def about(request):
    """ Handles requests for the about page """
    
    return views.About().render()

def edit(request, id):
    """ Handles requests for editing a note """
    
    logging.info("edit requested")
    source = None
    if request.method == 'POST':
        post_data = request.POST
        try:
            source = post_data["src"]
        except KeyError:
            logging.info("source field not found")
            return views.Redirect("home").render()

    notelist = get_notelist(users.get_current_user())
    note = dbutils.get_note_by_id(id, notelist)

    if source == "edit":
        logging.info("source is " + source)
        form = forms.AddForm(post_data)

        if not form.is_valid():
            return views.Edit(form, id, note).render()
        else:
            parser = NoteParser(form, id)
            parser.parse()
            save_note(parser.note, parser.tags, False)
            Messages.add(messages.SAVE_SUCCESS)
            return views.Redirect("home").render()
    else:
        return views.Edit(get_add_form(note), id, note).render()

def delete(request, id):
    """ Handles requests for deleting a Note """
    
    logging.info("delete requested")

    if not delete_note_by_id(id, get_notelist(users.get_current_user())):
        logging.error("could not delete note with id %s" % id )
    else: Messages.add(messages.DELETE_SUCCESS)
    return views.Redirect("home").render()

def details(request, id):
    """ Handles requests for seeing a Note's details """
    
    logging.info("details requested")
    note = get_note_by_id(id, get_notelist(users.get_current_user()))
    tags = get_tags_for_note(note)
    return views.Details(note, tags).render()

def share(request, id):
    """ Handles requests for sharing Notes """
    
    logging.info("share requested")

    source = None
    if request.method == 'POST':
        logging.info("post data found")
        post_data = request.POST

        try:
            source = post_data["src"]
        except KeyError:
            logging.error("source field not found")
            return views.Redirect("home").render()

    form = None
    user = users.get_current_user()
    note = get_note_by_id(id, get_notelist(user))
    
    if source == "share":
        logging.debug("source is " + source)
        form = forms.ShareForm(post_data)
        if form.is_valid():
            mail.send_mail(user.email(), form.clean_data["to"], form.clean_data["subject"], form.clean_data["text"])          
            Messages.add(messages.SHARE_SUCCESS)
            return views.Redirect("home").render()
    else: form = forms.ShareForm({"subject" : "%s shared a note with you!" % user.nickname(),
                                  "to" : "%s" % user.email(),
                                  "text" : note.text})

    return views.Share(form, note).render()

def filter(request, tag, page):
    """ Handles requests for filtering Notes by tags """
    
    notelist = get_notelist(users.get_current_user())

    if is_valid_tag(tag, notelist):    
        page = int(page)
        logging.info("filtering by tag %s on page %d" % (tag, page))
    
        return views.TagFilter(dbutils.get_or_insert_tag_by_name(tag, notelist), page).render()
    else: return views.Redirect("home").render()

def filter_no_page(request, tag):
    """ Handles requests for filtering Notes by tags """
    
    return filter(request, tag, 0)

def home (request):
    """ Handles the base request for the home page """
    
    logging.info("home requested")
    post_data = request.POST
    if request.method == 'POST':
        source = post_data["src"]
    else: 
        source = None

    form = None
    if source == "home":
        form = forms.AddForm(post_data)
        if form.is_valid():
            parser = NoteParser(form)
            parser.parse()
            save_note(parser.note, parser.tags)
            form = forms.AddForm()
            Messages.add(messages.SAVE_SUCCESS)  
    else: form = forms.AddForm()
    return views.Home(form).render()

def thumbnail(request, key):
    """ Handles thumbnail requests. """
    
    note = get_note_by_id(key, get_notelist(users.get_current_user()))
    return views.RawResponse(note.image, 'image/jpeg').render()

def browse (request, page):
    """ Handles page browsing requests """
    
    if page is None: page = 0
    page = int(page)
    if page == 0: v = views.Home(forms.AddForm(), page)
    else: v = views.Home(None, page)
    return v.render()
